import { defineStore } from 'pinia'
import { ref, watch } from 'vue'
import { getAllVersions, createVersion, publishVersion } from '@/api/version'
import type { Version } from '@/types/global'
import { useRouter } from 'vue-router'

export const useVersionStore = defineStore('version', () => {
  const versions = ref<Version[]>([])
  const currentVersion = ref<Version | null>(null)
  const loading = ref(false)
  const showVersionCreator = ref(false)
  const router = useRouter()

  watch(currentVersion, () => {
    if (currentVersion.value) {
      router.push('/')
    }
  })

  const refreshVersions = async () => {
    try {
      loading.value = true
      const data = await getAllVersions()
      versions.value = data
      if (data.length > 0 && !currentVersion.value) {
        currentVersion.value = data[0]
      }
    } catch (error) {
      console.error('获取版本列表失败:', error)
    } finally {
      loading.value = false
    }
  }

  const setVersion = async (newVersion: Version) => {
    await refreshVersions() // 刷新版本列表后再设置
    const found = versions.value.find(v => v.ver_code === newVersion.ver_code)
    if (found) {
      currentVersion.value = found
    }
  }

  // 初始加载
  refreshVersions()

  const addNewVersion = async (baseVer: string, newVer: string, description: string) => {
    try {
      loading.value = true
      await createVersion({
        baseVer,
        newVer,
        description
      })
      await refreshVersions()
      showVersionCreator.value = false
    } catch (error) {
      console.error('创建版本失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  const publishCurrentVersion = async () => {
    if (!currentVersion.value) return
    
    try {
      loading.value = true
      await publishVersion(currentVersion.value.ver_code)
      await refreshVersions()
    } catch (error) {
      console.error('发布版本失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  return {
    versions,
    currentVersion,
    loading,
    showVersionCreator,
    refreshVersions,
    setVersion,
    addNewVersion,
    publishCurrentVersion
  }
})
